package com.czl.module_service.fragment.sort

import com.alibaba.android.arouter.facade.annotation.Route
import com.czl.base.base.BaseFragment
import com.czl.base.config.AppConstants
import com.czl.base.data.bean.tengyun.SortBean
import com.czl.base.event.LiveBusCenter
import com.czl.base.util.DialogHelper
import com.czl.module_service.BR
import com.czl.module_service.R
import com.czl.module_service.adapter.OnDeleteListener
import com.czl.module_service.adapter.SortManagementAdapter
import com.czl.module_service.databinding.FragmentSortManagementBinding
import com.czl.module_service.extension.loadCompletedData
import com.czl.module_service.viewmodel.SortManagementViewModel

/**
 * @author by xubin,
 * @date on 2022/1/19.
 * PS: Not easy to write code, please indicate.
 */
@Route(path = AppConstants.Router.Service.F_SERVICE_SORT_MANAGEMENT)
class SortManagementFragment :
    BaseFragment<FragmentSortManagementBinding, SortManagementViewModel>() {

    private val mAdapter: SortManagementAdapter by lazy {
        SortManagementAdapter(this).apply {
            listener = object : OnDeleteListener {
                override fun onDelete(bean: SortBean) {
                    showDialog(bean)
                }
            }
        }
    }

    override fun initContentView(): Int {
        return R.layout.fragment_sort_management
    }

    override fun initVariableId(): Int {
        return BR.viewModel
    }

    override fun initData() {
        super.initData()
        viewModel.tvTitle.set("物品管理")
        viewModel.toolbarRightText.set("删除")
        initAdapter()
        reload()
    }


    private fun initAdapter() {
        binding.recyclerView.run {
            adapter = mAdapter
        }
    }

    override fun initViewObservable() {
        viewModel.uc.loadCompleteEvent.observe(this, { data ->
            this.loadCompletedData(
                data?.hasNextPage,
                viewModel.currentPage == 2,
                data != null,
                data?.total,
                data?.list,
                mAdapter,
                binding.recyclerView,
                binding.smartCommon
            )
        })
        LiveBusCenter.observePayResultEvent(this, {
            when (it.payType) {
                AppConstants.Constants.PAY_SUCCESS_TYPE -> {
                    reload()
                }
            }
        })

        viewModel.uc.touchEditEvent.observe(this, { data ->
            mAdapter.isEdit = data
        })
    }

    override fun reload() {
        binding.smartCommon.autoRefresh()
    }

    private fun showDialog(bean: SortBean) {
        DialogHelper.showNomarlDialog(requireContext(), "", "您确定要删除该物品吗?", oncancle = {

        }, onconfirm = {
            mAdapter.remove(bean)
        })
    }
}